package com.fmatos.amazingwallpapers.wallpaper.domain;

import android.graphics.Canvas;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

public abstract class  AbstractAmazingWallpaper implements AmazingWallpaper {

	private static final String TAG = AbstractAmazingWallpaper.class.getSimpleName();

	private SurfaceHolder holder;
	boolean visible;

	/**
	 * Method that perform the heavy work of drawing on the canvas,
	 * 
	 * @param canvas a valid canvas != null
	 */
	protected abstract void concreteDraw(Canvas canvas);

	@Override
	public void onSurfaceChanged(SurfaceHolder holder,int width, int height) {
		Log.i(TAG,"Surface changed, address " + holder.toString());
		this.holder = holder;
		draw(holder);
	}

	@Override
	public void onTouchEvent(MotionEvent event, SurfaceHolder holder) {

//		if ( visible && event.getAction() == MotionEvent.ACTION_DOWN ) {			
//			draw(holder);
//		}
		
		
	}
		

	@Override
	public void onVisibilityChanged(boolean visible) {
		Log.i(TAG,"Visibility = " + visible ); 
		this.visible = visible;
	}
	
	public boolean isVisible() {
		return visible;
	}

	@Override
	public void draw(SurfaceHolder holder) {

		if ( this.visible) {
			Canvas canvas = null;

			try{	
				// i suspect that this method is being called when the image is not on the foreground anymore
				canvas = holder.lockCanvas(); // some exceptions locking surface
				if (canvas != null ) {

					concreteDraw(canvas);

				}
			} catch (IllegalArgumentException e) {
				// having some problems locking the canvas?
				Log.e(TAG,"Lock exception " + e.getMessage());
			} finally {
				if (canvas != null) {
					try {
						if ( this.holder != holder ) {
							Log.e(TAG,"AAAAAA Unlock exception " ); // never happened
						}
						if ( visible == false ) {
							Log.e(TAG,"Invisible" ); // never happened
						}
						holder.unlockCanvasAndPost(canvas);
					} catch ( IllegalArgumentException e) {
						Log.e(TAG,"Unlock exception " + e.toString()); 
					}
				}
			}
		}
	}


}
